package jgl.vajra.management.part.mine.activity;

import android.text.TextUtils;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.management.R;
import jgl.vajra.management.bean.CarMemberBean;
import jgl.vajra.management.bean.LoginInfoBean;
import jgl.vajra.management.bean.MemberCenterBean;
import jgl.vajra.management.bean.MemberPriceBean;
import jgl.vajra.management.databinding.ActivityMemberPurchaseBinding;
import jgl.vajra.management.event.CarChooseEvent;
import jgl.vajra.management.event.PayStatusEvent;
import jgl.vajra.management.event.PaymentSuccessEvent;
import jgl.vajra.management.listener.MyToolbarViewListener;
import jgl.vajra.management.manager.AccountManager;
import jgl.vajra.management.manager.FragmentManager;
import jgl.vajra.management.manager.IntentManager;
import jgl.vajra.management.manager.PayManager;
import jgl.vajra.management.part.mine.contract.MemberPurchaseContract;
import jgl.vajra.management.part.mine.fragment.MemberTypeFragment;
import jgl.vajra.management.part.mine.viewModel.MemberPurchaseViewModel;
import jgl.vajra.management.widget.base.BaseFragmentAdapter;
import jgl.vajra.management.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.management.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.management.widget.giide.GlideImageLoader;
import jgl.vajra.management.widget.manager.RxJavaHttpManager;
import jgl.vajra.management.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.management.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.management.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.management.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.management.widget.utils.ToastUtils;
import jgl.vajra.management.widget.utils.UIUtils;

@CreateViewModel(MemberPurchaseViewModel.class)
public class MemberPurchaseActivity extends BaseMVVMActivity<MemberPurchaseViewModel, ActivityMemberPurchaseBinding> implements MemberPurchaseContract.View, BaseBindingItemPresenter<MemberPriceBean> {

    private List<Fragment> fragmentList = new ArrayList<>();
    private List<Fragment> fragmentList1 = new ArrayList<>();
    private List<MemberCenterBean.ContentBean> contentData = new ArrayList<>();
    List<MemberPriceBean> list = new ArrayList<>();
    private SingleTypeBindingAdapter addressPrice;
    private CarMemberBean carMemberBean;
    private int payType;
    private String orderId;
    private String logo;
    private int price;
    private int memberId;
    private String id;


    @Override
    public int getLayoutId() {
        return R.layout.activity_member_purchase;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);

        mBinding.toolbar.setMyToolbarViewListener(new MyToolbarViewListener() {
            @Override
            public void onRightTextClick() {
                super.onRightTextClick();
                IntentManager.toMemberRulesActivity(MemberPurchaseActivity.this);
            }
        });

        carMemberBean = getIntent().getParcelableExtra("itemData");

        if (!TextUtils.isEmpty(carMemberBean.logo)) {
            logo = carMemberBean.logo;
            mBinding.tvCarName.setText("名下豪车:" + carMemberBean.carNickname + "  型号:" + carMemberBean.alias + "  " + carMemberBean.name);
            mBinding.tvLogo.setText("车架号:" + carMemberBean.logo);
        }

        //默认支付类型为支付宝
        payType = 1;
        mBinding.ivAliPay.setSelected(true);

        LoginInfoBean loginInfo = AccountManager.getInstance().getLoginData(UIUtils.getContext());
        mBinding.tvName.setText(loginInfo.nickname);
        GlideImageLoader.onAvatarDisplayRound(mBinding.ivAvatar, loginInfo.avatar, null);

       /* for (int i = 0; i < list.size(); i++) {
            MemberCarTypeFragment listFragment = FragmentManager.getMemberCarTypeFragment();
            fragmentList.add(listFragment);
        }

        BaseFragmentAdapter adapters = new BaseFragmentAdapter(this.getSupportFragmentManager(), fragmentList);
        mBinding.viewPage.setAdapter(adapters);*/

        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        addressPrice = new SingleTypeBindingAdapter(this, null, R.layout.item_member_purchase);
        mBinding.recyclerView.setAdapter(addressPrice);
        addressPrice.setItemPresenter(this);

        requestNetData();
    }

    private void requestNetData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        mViewModel.getMemberCenterData(map);

        //获取订单号
        mViewModel.getRandomOrderNumber();
    }

    @Override
    public void onMyCar() {
    }

    @Override
    public void onAliPay() {
        payType = 1;
        mBinding.ivAliPay.setSelected(true);
        mBinding.ivWxPay.setSelected(false);
    }

    @Override
    public void onWXPay() {
        payType = 3;
        mBinding.ivWxPay.setSelected(true);
        mBinding.ivAliPay.setSelected(false);
    }

    @Override
    public void onDetermine() {
        if (TextUtils.isEmpty(logo)) {
            ToastUtils.showShort("请选择豪车");
            return;
        }

        if (TextUtils.isEmpty(id)){
            return;
        }

        orderId = AEACCoder.encrypt(id + "&&" + logo + "&&" + price+"&&"+memberId);
        if (payType == 1) {//支付宝支付
            PayManager.getInstance().payMemberAli(this, orderId);
        } else if (payType == 3) {//微信支付
            PayManager.getInstance().payMemberWx(this, orderId);
        }
    }

    @Override
    public void onCarType(boolean type) {
        int currentItem = mBinding.viewPage.getCurrentItem();
        if (type) {
            if (currentItem < contentData.size()) {
                mBinding.viewPage.setCurrentItem(currentItem + 1);
            }
        } else {
            if (currentItem > 0) {
                mBinding.viewPage.setCurrentItem(currentItem - 1);
            }
        }
    }

    @Override
    public void onMemberType(boolean type) {
        int currentItem = mBinding.viewPage1.getCurrentItem();
        if (type) {
            if (currentItem < contentData.size()) {
                mBinding.viewPage1.setCurrentItem(currentItem + 1);
            }
        } else {
            if (currentItem > 0) {
                mBinding.viewPage1.setCurrentItem(currentItem - 1);
            }
        }
    }

    @Override
    public void returnMemberCenterData(MemberCenterBean data) {
        contentData.clear();
        contentData.addAll(data.contentData);
        for (int i = data.contentData.size() - 1; i >= 0; i--) {
            if (data.contentData.get(i).tag == 1) {
                data.contentData.remove(i);
            }
        }

        for (int i = 0; i < data.contentData.size(); i++) {
            MemberTypeFragment listFragment = FragmentManager.getMemberTypeFragment(data.contentData.get(i));
            fragmentList1.add(listFragment);
        }

        BaseFragmentAdapter adapter1 = new BaseFragmentAdapter(this.getSupportFragmentManager(), fragmentList1);
        mBinding.viewPage1.setAdapter(adapter1);
        mBinding.viewPage1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                Logger.d(position + "测试数啊");
                setRecyclerViewData(position);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        setRecyclerViewData(0);

    }

    @Override
    public void returnRandomOrderNumberSuccess(String id) {
        this.id =id;
    }

    public void setRecyclerViewData(int position) {
        list.clear();
        price = contentData.get(position).monthFee;
        memberId=contentData.get(position).id;
        list.add(new MemberPriceBean(contentData.get(position).monthFee, "月会员", true));
        list.add(new MemberPriceBean(contentData.get(position).quarterFee, "季会员", false));
        list.add(new MemberPriceBean(contentData.get(position).yearFee, "年会员", false));
        addressPrice.refresh(list);
    }

    @Override
    public void onItemClick(int position, MemberPriceBean itemData) {
        if (itemData.isClick)
            return;
        for (int i = 0; i < list.size(); i++) {
            list.get(i).isClick = false;
        }
        list.get(position).isClick = true;
        price = itemData.price;
        addressPrice.refresh();
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCarChooseEvent(CarChooseEvent event) {
        logo = event.itemData.logo;
        mBinding.tvCarName.setText("名下豪车:" + event.itemData.titleName + "  型号:" + event.itemData.name + "  " + event.itemData.memberName);
        mBinding.tvLogo.setText("车架号:" + event.itemData.logo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayStatusEvent(PayStatusEvent event) {
        int statusType;
        if (event.status) {
            statusType = 1;
        } else {
            statusType = 2;
        }

        //微信支付成功或者失败回调,并调用后台接口
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", orderId);
        map.put("tag", event.tag);//tag=2并支付成功时：orderId=AES加密(订单号 + "&&" + 1)，tag=2并支付失败时：orderId=AES加密(订单号 + "&&" + 2
        RetrofitJsonManager.getInstance().getApiService().payMemberWxCallback(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(false, null) {
                    @Override
                    public void _onNext(String wxPayBean) {
                        if (event.status) {
                            EventBus.getDefault().post(new PaymentSuccessEvent());
                            finish();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage, int errorCode) {
                        super._onError(errorMessage, errorCode);
                        if (event.status) {
                            EventBus.getDefault().post(new PaymentSuccessEvent());
                            finish();
                        }
                    }
                });
    }
}
